package com.plugin.sharding;

import java.util.Collection;
import java.util.LinkedHashSet;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;

@Slf4j
@Data
public class TableShardingByString implements CommonTableShardingAlgorithm<String> {
	private String logicTableName;
	
	public TableShardingByString(String logicTableName) {
		this.logicTableName = logicTableName;
	}

	/**
	 * 查询条件是=的时候
	 */
	public String doEqualSharding(Collection<String> tableNames,
			ShardingValue<String> shardingValue) {
		String fixedTableName = Utils.genTableName(logicTableName, shardingValue.getValue());
		if(tableNames.contains(fixedTableName)) {
			log.info("tableName is : {}", fixedTableName);
			return fixedTableName;
		}
		log.info("没有合适找到对应的表名： modStr : {}", Utils.getShardingIndex(shardingValue.getValue()));
		throw new IllegalArgumentException("没有合适找到对应的表名： " + Utils.getShardingIndex(shardingValue.getValue()));
	}

	/**
	 * 查询条件是in的时候
	 */
	public Collection<String> doInSharding(Collection<String> tableNames,
			ShardingValue<String> shardingValue) {
		Collection<String> result = new LinkedHashSet<String>(tableNames.size());
		for (String queryValue : shardingValue.getValues()) {
			String fixedTableName = Utils.genTableName(logicTableName, queryValue);
			if(tableNames.contains(fixedTableName)) {
				log.info("tableName is : {}", fixedTableName);
				result.add(fixedTableName);
			} else {
				log.info("没有合适找到对应的表名： modStr : {}", Utils.getShardingIndex(queryValue));
			}
		}
		return result;
	}

	/**
	 * 查询条件是分片是String类型的时候，between无需实现
	 */
	public Collection<String> doBetweenSharding(Collection<String> tableNames,
			ShardingValue<String> shardingValue) {
		return null;
	}

}
